<?php


namespace catchAdmin\customs\controller;


use cainiao\api\v1\Link;
use catchAdmin\customs\model\CnOrder as cnOrderModel;
use catchAdmin\externalGoods\model\Goods as externalGoodsModel;
use catcher\base\CatchRequest as Request;
use catcher\CatchAuth;
use catcher\CatchResponse;
use catcher\Code;
use houniao\api\v1\Order as HNOrderApi;
use think\facade\Db;
use think\helper\Str;
use xinsheng\api\v1\Pay;

class CnOrder
{

    public function __construct(cnOrderModel $cnOrderModel)
    {
        $this->cnOrderModel  = $cnOrderModel;
    }


    //推送-创建订单
    public function push($id,CatchAuth $auth){
        $user = $auth->user();

        $order  = $this->cnOrderModel
            ->withoutField('created_at,updated_at,deleted_at,tenant_id,creator_id')
            ->find($id);

        if(!$order){
            return CatchResponse::fail('订单不存在');
        }
        if($order['push_status'] !== '未推送'){
            return CatchResponse::fail('订单已经推送，不可重复操作');
        }

        $data = $order->toArray();

        unset($data['_ext_data']);

        $data['receiverInfo'] = json_decode($data['receiverInfo'],true);
        $data['senderInfo'] = json_decode($data['senderInfo'],true);
        $data['refunderInfo'] = json_decode($data['refunderInfo'],true);
        $data['orderItemList'] = json_decode($data['orderItemList'],true);
        $data['orderAmountInfo'] = json_decode($data['orderAmountInfo'],true);
        $data['customsDeclareInfo'] = json_decode($data['customsDeclareInfo'],true);
        //--------//
        $data['extendFields'] = json_decode($data['extendFields'],true);
        $data['departureInfo'] = json_decode($data['departureInfo'],true);
        $data['logisticsServices'] = json_decode($data['logisticsServices'],true);

        foreach ($data as $key => $value){
            //过滤空数组
            if(is_array($value) && 0 == count($value)){
                unset($data[$key]);
            }
            //过滤空字符串
            if($value == ''){
                unset($data[$key]);
            }
            //过滤一些其他字段

        }

//        dd($data);

        try {
            $cainiaoApi = new Link;
            $result =  $cainiaoApi->GLOBAL_SALE_ORDER_NOTIFY($data);

            if($result['success'] == 'true'){//成功
                $order->cnOrderCode = $result['cnOrderCode'];
                $order->push_status = '已推送';
                $order->save();
            }else{
                return CatchResponse::fail( '推送失败');
            }
        } catch (\Exception $e) {
            return CatchResponse::fail( $e->getMessage());
        }

        return CatchResponse::success($result,'下单成功');




        //新生支付-支付
        /*
        $xinshengApi = new Pay();
        $arr = [
            'merOrderId'=>Str::random(20,1),
            'displayName'=>"面膜",
            'goodsName'=>"面膜",
            'goodsCount'=>1,
            'goodsType'=>"06",
            'orderAmount'=>100,
            'orderCurrencyCode'=>"CNY",
            'tradeType'=>"0004",
            'payType'=>"4",
            'orgCode'=>'alipay',
            'payCurrencyCode'=>"CNY",
            'settleCurrencyCode'=>"CNY",
            'shareFlag'=>"0",
            'returnUrl'=>"http://cross.qekj.net/callback/xinsheng",
            'noticeUrl'=>"http://cross.qekj.net/callback/xinsheng",
            'customerType'=>"1",
            'customerName'=>'徐颖',
            'customerIdNo'=>'320923199610233610',
            'customerTel'=>'15150688887'
        ];

        try {
            dd($xinshengApi->apiPay($arr));
        }catch (\Exception $exception ){
            dd($exception->getMessage());
        }
        */


        //新生支付-报关
        /*
        $xinshengApi = new Pay();
        $arr = [
            'eportCode'=>'00',
            'merOrderId'=>'06541316642936132769',
            'currencyCode'=>'CNY',
            'eCompanyCode'=>'460116287K',
            'eCompanyName'=>'新生支付有限公司',
            'payTransactionNo'=>'1022307061126037112',
            'actionType'=>'1',//2修改
            'payerName'=>'徐颖',
            'payerType'=>'01',
            'payerId'=>'320923199610233610',
            'noticeUrl'=>'http://cross.qekj.net/callback/xinsheng'
        ];

        try {
            dd($xinshengApi->customsApply($arr));
        }catch (\Exception $exception ){
            dd($exception->getMessage());
        }
        */

        $cainiaoApi = new Link;

        $content = [
        ];
        dd($cainiaoApi->GLOBAL_SALE_ORDER_NOTIFY($content));

        $linkUrl = 'http://link.cainiao.com/gateway/link.do';

        $content = [
            'ownerUserId'=>'2215491449369',
            'storeCode'=>'1',
            'pageNo'=>1,
            'pageSize'=>50,
            'businessUnitId'=>1

        ];     // 如果接口配置为json格式，这儿内容就是json，否则是xml格式

        $appSecret = 'A4anLq32vpai5Bsi85s0P9w5S8r462r2';    // APPKEY对应的秘钥

        $cpCode = 'fa605fbd52b5a6c69c220c6e7e526a7b';     //调用方的CPCODE

        $msgType = 'GLOBAL_SALE_ORDER_NOTIFY';    //调用的API名

        $toCode = '';        //调用的目标TOCODE，有些接口TOCODE可以不用填写

        $digest = base64_encode(md5(json_encode($content).$appSecret, true));     //生成签名

        echo 'digest is '.$digest."\n";

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $linkUrl);

        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/x-www-form-urlencoded']);

        //  dd(urlencode(json_encode($content)));

        $post_data = 'msg_type='.$msgType
            .'&logistic_provider_id='.urlencode($cpCode)
            .'&data_digest='.urlencode($digest)
            .'&logistics_interface='.urlencode(json_encode($content))
            .'&to_code='.$toCode
        ;

        //dd(json_encode($post_data));
//        rawurlencode()
        echo "Post body is: \n".json_encode($post_data)."\n";

        dd(json_encode($post_data));

        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_POST, 1);

        echo "Start to run...\n";
        $output = curl_exec($ch);
        curl_close($ch);

        dd($output);

        // $result = simplexml_load_string($output);
        // dd(json_decode(json_encode($result,JSON_UNESCAPED_UNICODE),true));


        echo "Finished, result data is: \n".json_encode($output);


        dd(22);




        $xinshengApi = new Pay();
//        $arr  = ["currency"=>"USD","targetCurrency"=>"CNY","resvFld1"=>"","resvFld2"=>""];
        $arr = [
            'merOrderId'=>Str::random(20,1),
            'displayName'=>"牛肉汤",
            'goodsName'=>"牛肉粉丝汤",
            'goodsCount'=>1,
//            'goodsType'=>'01',
            'orderAmount'=>1,
            'orderCurrencyCode'=>"CNY",
            'tradeType'=>"0002",
            'payType'=>"4",
            'orgCode'=>'alipay',
//            'payerAccount'=>''
            'payCurrencyCode'=>"CNY",
            'settleCurrencyCode'=>"CNY",
            'shareFlag'=>"0",
            'returnUrl'=>"http://cross.qekj.net/callback/xinsheng",
            'noticeUrl'=>"http://cross.qekj.net/callback/xinsheng",
//            'platformId'=>''
        ];

//        $arr = [
//            'cardNo'=>'6230200052318404'
//        ];

//        dd($arr);

//        try {
//            dd($xinshengApi->apiPay($arr));
//
//        }catch (\Exception $exception ){
//            dd($exception->getMessage());
//        }


//        $arr = [
//            'eportCode'=>'00',
//            'merOrderId'=>'43734681455402259457',
//            'currencyCode'=>'CNY',
//            'eCompanyCode'=>'460116287K',
//            'eCompanyName'=>'新生支付有限公司',
//            'payTransactionNo'=>'1022306131635037011',
//            'actionType'=>'1',//2修改
//            'payerName'=>'徐颖',
//            'payerType'=>'01',
//            'payerId'=>'320923199610233610',
//            'noticeUrl'=>'http://cross.qekj.net/callback/xinsheng'
//        ];


        $arr = [
            'queryType'=>'1',
            'orderType'=>'1',
            'oldMerOrderId'=>'43734681455402259457'
        ];


        //dd($xinshengApi->customsApply($arr));

        try {
//            dd($xinshengApi->customsApply($arr));
            dd($xinshengApi->orderQuery($arr));

        }catch (\Exception $exception ){
            dd($exception->getMessage());
        }


        dd(222);
//        //取消
//        dd((new \houniao\api\v1\Order())->cancel([
//            'order_no'=>'2023060911739'
//        ]));

//        dd((new \houniao\api\v1\Order())->info([
//            'order_no'=>'2023060911719'
//        ]));

        $user = $auth->user();

        $res  = $this->hnOrderModel
            ->withoutField('id,created_at,deleted_at,tenant_id,creator_id')
            ->find(1)->toArray();
        // dd($res);
        $data = $res;
        $data['order_goods'] = [
//            [
//                'goods_spu'=>'BS00000162',
//                'sku_id' => "100030881",
//                'goods_num'=> 2
//            ]
//            [
//                'goods_spu'=>'GM00032524',
//                'sku_id' => "100031054",
//                'goods_num'=> 2
//            ]
            [
                'goods_spu'=>'HW00014428',
                'sku_id' => "100030507",
                'goods_num'=> 2
            ]//海外直邮
        ];

        $data['source_order_no'] = mt_rand(1,1000000);
        $data['area_id'] = 130502;
        $data['id_card'] = '320923199610233610';
        $order_id = $data['order_id'];
        unset($data['order_id']);
//        unset($data['id_card_front_img']);

//        dd((new HNOrderApi())->freight([
//            'sku_id' => "100030881",
//            'goods_num'=> 2,
//            'area_id'=> '130502'
//        ]));

        $orderResult = (new HNOrderApi())->createOrder($data)['data'];

        dd($orderResult);die();

        $orderDetailArr = [];
        foreach ($orderResult['order_items'] as $value){
            $ord = $value;
            $ord['order_id'] = $order_id;
            $ord['order_detail_id'] = $value['order_no'];
            $ord['tenant_id'] = $user['tenant_id'];
            $ord['creator_id'] = $user['id'];
            $ord['goods_spu'] = $value['order_goods']['goods_spu'];
            $ord['goods_sku'] = $value['order_goods']['sku_id'];
            $ord['goods_price'] = $value['order_goods']['goods_price'];
            $ord['goods_num'] = $value['order_goods']['goods_num'];
            $ord['goods_name'] = (new externalGoodsModel)->where('goods_spu',$ord['goods_spu'])->value('goods_name');

            $orderDetailArr[] = $ord;
        }

        Db::startTrans();
        try {
            //推送后，创建明细单
            $this->hnOrderDetailModel->saveAll($orderDetailArr);

            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail($exception->getMessage());
        }

        return CatchResponse::success([],'success');
    }

    //查询最新订单消息
    public function queryOrder($id,CatchAuth $auth, Request $request){
        $user = $auth->user();

        $order  = $this->cnOrderModel
            ->withoutField('created_at,updated_at,deleted_at,tenant_id,creator_id')
            ->find($id);

        if(!$order){
            return CatchResponse::fail('订单不存在');
        }

        $data = [
            'userId'=>$order['ownerUserId'],
            'lgOrderCode'=>$order['cnOrderCode']
        ];

        try {
            $cainiaoApi = new Link;
            $result =  $cainiaoApi->CROSSBORDER_LOGISTICS_DETAIL_QUERY($data);


            if($result['success'] != 'true'){
                return CatchResponse::fail( '查询失败');
            }

//            if($result['success'] == 'true'){//成功
//
//                $order->push_status = $result['nodeList'][0]['packageStatus']['logisticStatusDesc'];
//                $order->mailNo = $result['nodeList'][0]['mailNo'];
//                $order->partnerCode = $result['nodeList'][0]['partnerList'][0]['partnerCode'];
//                $order->partnerName = $result['nodeList'][0]['partnerList'][0]['partnerName'];
//                $order->save();
//            }else{
//                return CatchResponse::fail( '查询失败');
//            }

        } catch (\Exception $e) {
            return CatchResponse::fail($e->getMessage());
        }

        return CatchResponse::success($result,'查询成功');
    }


    //列表
    public function index(CatchAuth $auth, Request $request)
    {
        $user = $auth->user();
        return CatchResponse::paginate($this->cnOrderModel->getList($user['tenant_id']));
    }

    //修改支付单&身份号码
    public function modifyInfo($id,CatchAuth $auth, Request $request){
        $order  = $this->cnOrderModel
            ->field('externalOrderCode,ownerUserId as merchantId,externalShopId as extUserId,orderSource,customsDeclareInfo,cnOrderCode')
            ->find($id);

        if(!$order){
            return CatchResponse::fail('订单不存在');
        }

        $orderData = $order->toArray();
        $orderData['payType'] = $order->pay_type;
        $customsDeclareInfo = $orderData['customsDeclareInfo'];
        unset($orderData['customsDeclareInfo']);

        $requestData = array_filter($request->only(['buyerName','buyerIDNo','payOrderId','buyerIDCardFrontPic','idCardBackPicUrlIndex']));
        $data = array_filter(array_merge($requestData,$orderData));

        //dd(array_keys($requestData));

        try {
            $cainiaoApi = new Link;
            $result =  $cainiaoApi->CROSSBORDER_ORDER_INFO_MODIFY($data);

            if($result['success'] != 'true'){
                return CatchResponse::fail( '修改失败' . $result['errorMsg']);
            }else{
                $saveData = array_merge($customsDeclareInfo,$requestData);
                $order->customsDeclareInfo = $saveData;
                $order->save();
                //$order->allowField(array_keys($requestData))->save($requestData);
            }

        } catch (\Exception $e) {
            return CatchResponse::fail($e->getMessage());
        }

        return CatchResponse::success($result,'修改成功');
    }
}